package com.shanghaionstar.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.mvp.base.core.PermissionCall;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.sqlite.entities.LandingsPageEntityNew;
import com.onstar.cn.weight.CountView;
import com.onstar.cn.weight.CustomImageView;
import com.shanghaionstar.BuildConfig;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.IWebType;
import com.shanghaionstar.activity.webview.handler.LandingBannerHandler;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.home.adapter.LoadingPagerAdapter;
import com.shanghaionstar.iview.ILoadingView;
import com.shanghaionstar.presenter.LoadingPresenter;

import java.util.List;

import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by 7828wc on 2016/6/21.
 */
@ContentView(R.layout.onstar_loading)
public class LoadingActivity extends BaseActivity implements ILoadingView<LandingsPageEntityNew> {
    private boolean partnerAutoNavFlag = false;
    private String share3RDFlag = "";
    @FindViewById
    private ViewAnimator loading_layout;
    //    @FindViewById(background = R.drawable.loading)
    @FindViewById(background = R.drawable.loading_notxt_min)
    private CustomImageView logo_bg;
    @FindViewById
    private ViewPager guide_vp;
    private boolean isBanner = false;
    private LoadingPresenter presenter;
    private boolean isShowLandingPage = false;
    private LandingsPageEntityNew landingPage;
    private Subscription subscription;
    private static final int LOAD_TIME = 1000;
    @FindViewById
    private TextView txt_loading_launch_txt;

    @FindViewById
    private CountView jump_view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        partnerAutoNavFlag = getIntent().getBooleanExtra(Constants.PARTNER_AUTONAV_FLAG, false);
        share3RDFlag = getIntent().getStringExtra(Constants.PARTNER_3RD_FLAG);
        presenter = new LoadingPresenter(getScheduler());
        presenter.setView(this);
        startService(new Intent(this, LandingPageDLService.class));
        registLandingPageReceive();
        requestRunTimePermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionCall() {
            @Override
            public void requestSuccess() {
                presenter.loadDBLandingPage();
                showAnimation();
            }

            @Override
            public void refused() {
                Toast.makeText(LoadingActivity.this, "please open the write permission", Toast.LENGTH_SHORT).show();
            }
        });

    }


    @Override
    public void showLandingPage(LandingsPageEntityNew landingPage) {
        if (landingPage != null) {
            this.landingPage = landingPage;
            isBanner = true;
        }
    }

    private void registLandingPageReceive() {
        subscription = RxBus.getDefault().toObserverable(RxConstants.LANDING_PAGE, LandingsPageEntityNew.class).subscribe(new Action1<LandingsPageEntityNew>() {
            @Override
            public void call(LandingsPageEntityNew landingsPageEntity) {
                if (landingsPageEntity != null) {
                    LoadingActivity.this.landingPage = landingsPageEntity;
                }
            }
        });
    }

    /**
     * 显示动画 @Title: showAnimation @Description: TODO @param 设定文件 @return void
     * 返回类型 @throws
     */
    private boolean isClickBanner = false;

    private void showAnimation() {
        AlphaAnimation animation = new AlphaAnimation(0.3f, 1.0f);
        animation.setDuration(LOAD_TIME);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (!isBanner) {
                    boolean hasGuide = PreferencesUtls.getInstance(LoadingActivity.this).getBoolean(Constants.LOADING_GUIDE, false);
                    if (hasGuide) {
                        launchMain();
//                        loading_layout.setDisplayedChild(1);
//                        presenter.initData();
                    } else {
                        //加载引导页
                        loading_layout.setDisplayedChild(1);
                        presenter.initData();
                    }
                } else {
                    isBanner = false;
                    jump_view.setAnimationListener(new CountView.AnimationListener() {
                        @Override
                        public void onAnimationEnd() {
                            jump_view.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    launchMain();
                                }
                            });
                            if (!isClickBanner) {
                                launchMain();
                            }
                        }

                        @Override
                        public void onAnimationStart() {

                        }
                    });

                    LogManager.getInstance().d("the landingpage duration" + landingPage.getDuration());
                    jump_view.playAnimator(360, CommonUtil.isAllNumerice(landingPage.getDuration()) ? Integer.valueOf(landingPage.getDuration()) : 3000);

                    ImageLoader.getInstance().displayImage("file://" + landingPage.getFilePath(), logo_bg, new ImageLoadingListener() {

                        @Override
                        public void onLoadingStarted(String s, View view) {

                        }

                        @Override
                        public void onLoadingFailed(String s, View view, FailReason failReason) {

                        }

                        @Override
                        public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                            jump_view.setVisibility(View.VISIBLE);
                            jump_view.setEnabled(true);
                            jump_view.setClickable(true);
                            logo_bg.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    isClickBanner = true;
                                    Bundle bundle = new Bundle();
                                    Intent it = new Intent(LoadingActivity.this, CommonWebViewActivity.class);
                                    bundle.putString("receiveType", getIntent().getStringExtra("receiveType"));
                                    bundle.putString("uri", getIntent().getStringExtra("uri"));
                                    bundle.putString("title", getIntent().getStringExtra("title"));
                                    bundle.putString("thumbnailUrl", landingPage.getThumbnailUrl());
                                    bundle.putBoolean("canShare", "1".equals(landingPage.getCanShare()));//1能分享；0不能分享

                                    bundle.putBoolean(Constants.PARTNER_AUTONAV_FLAG, partnerAutoNavFlag);
                                    bundle.putString(Constants.PARTNER_3RD_FLAG, share3RDFlag);
                                    bundle.putSerializable(Constants.PARTNER_3RD_POI, getIntent().getSerializableExtra(Constants.PARTNER_3RD_POI));
                                    if (adaper != null) {
                                        adaper.onFinish();
                                    }
                                    WebDataEntity mWebData = new WebDataEntity();
                                    mWebData.setLinkUrl(landingPage.getUrl());
//                                    mWebData.setTopTitle("广告页");
                                    mWebData.setCanGoBack(false);
                                    mWebData.setWhat(IWebType.TYPE_LANDING_BANNER);
                                    mWebData.setClzName(LandingBannerHandler.class.getName());
                                    mWebData.setFromPage(LoadingActivity.class.getSimpleName());
                                    bundle.putParcelable(IWebType.KEY_WEB_DATA, mWebData);
                                    CommonWebViewActivity.launchCommonWeb(LoadingActivity.this, bundle, mWebData);
                                    finish();
                                }
                            });
                        }

                        @Override
                        public void onLoadingCancelled(String s, View view) {

                        }
                    });
//                    AlphaAnimation landingPageAnimation = new AlphaAnimation(0.3f, 1.0f);
//                    landingPageAnimation.setDuration(
//                            !CommonUtil.isNull(landingPage.getDuration()) ? Long.parseLong(landingPage.getDuration()) : LOAD_TIME);
//                    landingPageAnimation.setAnimationListener(this);
//                    loading_layout.startAnimation(landingPageAnimation);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        txt_loading_launch_txt.setText(getString(R.string.loading_launch_txt, BuildConfig.VERSION_NAME));
        loading_layout.startAnimation(animation);
    }

    @Override
    public BasePresenter getPresenter() {
        return presenter;
    }

    @Override
    public void setLoading(boolean isLoading) {
    }

    @Override
    public void onResponseError(OnStarException e) {
    }

    @Override
    public void onReponseSuccess(LandingsPageEntityNew object) {
    }

    private LoadingPagerAdapter adaper;

    @Override
    public void setupViewPager(final List<View> views) {
        adaper = new LoadingPagerAdapter(views);
        guide_vp.setAdapter(adaper);
        presenter.getEdge(guide_vp);
        final int len = views.size();
        initDots(len);
        final Button btn = (Button) views.get(views.size() - 1).findViewById(R.id.experience_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PreferencesUtls.getInstance(LoadingActivity.this).putBoolean(Constants.LOADING_GUIDE, true);
                launchMain();
            }
        });
        guide_vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrollStateChanged(int arg0) {
                if (presenter.onPageScrolled())
                    launchMain();
            }

            @Override
            public void onPageSelected(int arg0) {
                setCurDot(arg0, len);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }
        });
    }

    /**
     * 这只当前引导小点的选中
     */
    private void setCurDot(int position, int len) {
        if (position < 0 || position > len - 1 || currentIndex == position) {
            return;
        }
       /* dots[position].setEnabled(false);
        dots[currentIndex].setEnabled(true);*/
        dots[currentIndex].setImageResource(R.drawable.l_d_u);
        dots[position].setImageResource(R.drawable.l_d_s);
        currentIndex = position;
    }

    private ImageView[] dots;
    private int currentIndex;

    private void initDots(int len) {
        LinearLayout ll = (LinearLayout) findViewById(R.id.ll);

        dots = new ImageView[len];

        //循环取得小点图片
        for (int i = 0; i < len; i++) {
            dots[i] = (ImageView) ll.getChildAt(i);
//            dots[i].setEnabled(true);//都设为灰色
//            dots[i].setOnClickListener(this);
            dots[i].setImageResource(R.drawable.l_d_u);
            dots[i].setTag(i);//设置位置tag，方便取出与当前位置对应
        }

        currentIndex = 0;
        dots[currentIndex].setImageResource(R.drawable.l_d_s);
//        dots[currentIndex].setEnabled(false);//设置为白色，即选中状态
    }

    private void launchMain() {
        Intent it = new Intent(LoadingActivity.this, MainTabActivity.class);
        it.putExtra("receiveType", getIntent().getStringExtra("receiveType"));
        it.putExtra("uri", getIntent().getStringExtra("uri"));
        it.putExtra("title", getIntent().getStringExtra("title"));
        it.putExtra(Constants.PARTNER_AUTONAV_FLAG, partnerAutoNavFlag);
        it.putExtra(Constants.PARTNER_3RD_FLAG, share3RDFlag);
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constants.PARTNER_3RD_POI, getIntent().getSerializableExtra(Constants.PARTNER_3RD_POI));
        it.putExtras(bundle);
        startActivity(it);
        if (adaper != null) {
            adaper.onFinish();
        }
        finish();


//                Intent intent=new Intent(this,CommonWebViewActivity.class);
//                //        intent.putExtra("linkUrl","https://idt1.onstar.com.cn/mweb/mweb-main/static/OnStar-MA7.0-h5/html/car-assessment/valuation.html");
//                intent.putExtra("linkUrl","file:///android_asset/test.html");
//
//                intent.putExtra("topTitle","Test");
//                intent.putExtra("canGoBack",true);
//                startActivity(intent);
//                finish();
    }

    @Override
    public Activity onActivity() {
        return this;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        this.setIntent(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscription != null) {
            subscription.unsubscribe();
            subscription = null;
        }
    }
}